package com.gxgy.app.service.imp;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxgy.app.doman.dto.OrderDto;
import com.gxgy.app.doman.po.Goods;
import com.gxgy.app.doman.po.Order;
import com.gxgy.app.doman.po.User;
import com.gxgy.app.doman.vo.OrderVo;
import com.gxgy.app.mapper.GoodsMapper;
import com.gxgy.app.mapper.OrderMapper;
import com.gxgy.app.mapper.UserMapper;
import com.gxgy.app.service.OrderService;
import com.gxgy.app.task.OrderTask;
import com.gxgy.common.exception.ServiceException;
import com.gxgy.common.utils.DateUtils;
import com.gxgy.constant.HealthConstant;
import com.gxgy.quartz.util.ScheduleUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisTemplate redisTemplate;
    @Override
    public boolean downOrder(OrderDto orderDto) {
        // 校验订单
        Goods goods = goodsMapper.selectById(orderDto.getGoodsId());
        if(ObjectUtil.isEmpty(goods)){
            throw new ServiceException("订单不存在");
        }

        User user = userMapper.selectById(orderDto.getUserId());
        if(ObjectUtil.isEmpty(user)){
            throw new ServiceException("账号状态异常");
        }
        // 校验全部通过，增加订单
        Order order = new Order();
        BeanUtil.copyProperties(orderDto, order);
        // 给订单设置编号
        order.setOrderNo(generateTaskCode());
        order.setUserId(user.getId());
        order.setStatus(HealthConstant.ORDER_STATUS_UNPAID);
        order.setCreateBy(user.getName());
        order.setCreateTime(LocalDateTime.now());
        return this.save(order);
    }

    @Override
    public List<OrderVo> getOrderListByUserId(Long userId) {
        User user = userMapper.selectById(userId);
        if(ObjectUtil.isEmpty(user)){
            throw new ServiceException("用户不存在");
        }
        List<Order> orders = orderMapper.selectList(new LambdaQueryWrapper<Order>()
                .eq(Order::getUserId, userId)
                .orderByDesc(Order::getCreateTime));
        return getOrderVos(orders);
    }

    @Override
    public List<OrderVo> getOrderListByUserIdAndStatus(Long userId, Long[] status) {
        User user = userMapper.selectById(userId);
        if(ObjectUtil.isEmpty(user)){
            throw new ServiceException("用户不存在");
        }
        List<Order> orders = orderMapper.selectList(new LambdaQueryWrapper<Order>()
                .eq(Order::getUserId, userId)
                .in(Order::getStatus, status));
        return getOrderVos(orders);
    }

    @Override
    public boolean updateOrder(Order order) {
        // 判断订单，如果是已经付款或者退款中 则先更改，再开一个线程，过10秒状态 + 1再更新
        boolean result = false;
        Long status = order.getStatus();
        if(HealthConstant.ORDER_STATUS_PAID.equals(status) || HealthConstant.ORDER_REFUND.equals(status)){
            //先更改，再开一个线程，过10秒状态 + 1再更新
            result = orderMapper.updateById(order) > 0;
            // 开启一个线程，等待10秒更新状态
            new Thread(new OrderTask(order, orderMapper)).start();
        }else {
            result = orderMapper.updateById(order) > 0;
        }
        return result;
    }

    /**
     * 传入order 对象，返回VO对象，查询数据库回去当前order 对应的商品
     */
    private List<OrderVo> getOrderVos(List<Order> orders) {
        ArrayList<OrderVo> orderVos = new ArrayList<>();
        for(Order order: orders){
            // 构造返回的VO对象
            OrderVo orderVo = new OrderVo();
            // 拷贝属性
            BeanUtil.copyProperties(order, orderVo);
            // 查询该订单下的商品
            Goods goods = goodsMapper.selectById(order.getGoodsId());
            orderVo.setGoods(goods);
            orderVos.add(orderVo);
        }
        return orderVos;
    }

    /**
     * 生成订单编号
     */
    private String generateTaskCode(){
        // 获取当前日期，格式化为yyyyMMdd格式
        String dateStr = DateUtils.getDate().replaceAll("-", "");
        String key = "eat.task.code" + dateStr;
        // 判断key 是否存在
        if(!redisTemplate.hasKey(key)){
            // ky 不存在 设置初始值为1 设置过期时间一天
            redisTemplate.opsForValue().set(key, 1, Duration.ofDays(1));
            // 返回编号
            return dateStr + "0001";
        }
        // 如果key 存在 计数器 + 1，在确保字符串是长度为4位就可以了
        return dateStr +  StrUtil.padPre(redisTemplate.opsForValue().increment(key).toString(), 4, "4");
    }
}
